package com.central.common.handler;

import cn.hutool.json.JSONUtil;
import com.central.common.model.ColumnInfo;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedJdbcTypes;
import org.apache.ibatis.type.MappedTypes;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

/**
 * @author Tindy
 * @date 2021/6/23
 * @describe
 */
@MappedJdbcTypes(JdbcType.VARCHAR)  // 数据库类型
@MappedTypes({List.class})          // java数据类型
public class ListColumnToStringHandler extends BaseTypeHandler<List<ColumnInfo>> {

    @Override
    public void setNonNullParameter(PreparedStatement preparedStatement, int i, List list, JdbcType jdbcType) throws SQLException {
        preparedStatement.setString(i, JSONUtil.toJsonStr(list));
    }

    @Override
    public List getNullableResult(ResultSet resultSet, String s) throws SQLException {
        List jsonArray = JSONUtil.toList(JSONUtil.parseArray(resultSet.getString(s)),ColumnInfo.class);
        return jsonArray;
    }

    @Override
    public List getNullableResult(ResultSet resultSet, int i) throws SQLException {
        List jsonArray = JSONUtil.toList(JSONUtil.parseArray(resultSet.getString(i)),ColumnInfo.class);
        return jsonArray;
    }

    @Override
    public List getNullableResult(CallableStatement callableStatement, int i) throws SQLException {
        List jsonArray = JSONUtil.toList(JSONUtil.parseArray( callableStatement.getString(i)),ColumnInfo.class);
        return jsonArray;
    }
}

